package com.novel.resources.impl;

import cn.hutool.core.io.file.FileNameUtil;
import cn.xuyanwu.spring.file.storage.FileStorageService;
import com.novel.common.resource.IResourceService;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.ComponentScan;

import java.io.InputStream;

/**
 * 资源接口实现类
 *
 * @author novel
 * @since 2023/8/21 19:50
 */
@Slf4j
@MapperScan({"com.novel.resources.mapper"})
@ComponentScan({"com.novel.resources"})
public class ResourcesImpl implements IResourceService {
    private final FileStorageService fileStorageService;

    public ResourcesImpl(FileStorageService fileStorageService) {
        this.fileStorageService = fileStorageService;
        log.info("ResourcesImpl init");
    }

    @Override
    public String getFileUrl(String sourceUrl) {
        var info = fileStorageService.getFileInfoByUrl(sourceUrl);
        return info != null ? info.getUrl() : null;
    }

    @Override
    public boolean upLoadFile(String sourceUrl, String destPath) {
        var name = FileNameUtil.getName(destPath);
        var path = destPath.replace(name, "");
        var info = fileStorageService.of(sourceUrl).setPath(path).setSaveFilename(name).setName(destPath).setOriginalFilename(name).upload();
        return info != null;
    }

    @Override
    public boolean upLoadFile(InputStream source, String destPath) {
        var name = FileNameUtil.getName(destPath);
        var path = destPath.replace(name, "");
        var info = fileStorageService.of(source).setPath(path).setSaveFilename(name).setName(name).setOriginalFilename(name).upload();
        return info != null;
    }

    @Override
    public void download(String filePath, String localPath) {
        fileStorageService.download(filePath).file(localPath);
    }

    @Override
    public boolean delete(String filePath) {
        return fileStorageService.delete(filePath);
    }

    @Override
    public byte[] readBytes(String filePath) {
        return fileStorageService.download(filePath).bytes();
    }
}
